package com.calvin.study.rabbitmq.consumer;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.calvin.study.service.OrderService;
import com.rabbitmq.client.Channel;

import cloud.alibaba.study.entity.order.Order;
import cloud.alibaba.study.utils.GsonUtil;

@Component
public class RabbitMqConsumer {
	
	@Autowired
	private OrderService orderService;
	
	@RabbitListener(queues="order.seckill.order.queue")
	@RabbitHandler
	public void seckillOrderListener(Order order, Channel channel,Message message) throws Exception {
		long deliveryTag = 0 ;
		try {
			//当前消息是否重新派发
			//Boolean redelivered = message.getMessageProperties().getRedelivered();
			deliveryTag = message.getMessageProperties().getDeliveryTag();

			orderService.placeOrderV2(order);
			channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
		} catch (Exception e) {
			//如果发生异常,则进行消费重试机制
			channel.basicNack(deliveryTag, false, false);
		}
	}
	
	public static void main(String[] args) {
		try {
			Class<?> clazz = Class.forName("cloud.alibaba.study.entity.order.Order");
			String json = "{'orderNo':'11111'}";
			Order order = (Order) GsonUtil.fromJson(json, clazz);
			System.out.println(order);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
